package fun.stgoder.easydarwin.jobs.ctl;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import fun.stgoder.easydarwin.jobs.comm.Code;
import fun.stgoder.easydarwin.jobs.comm.Constants;
import fun.stgoder.easydarwin.jobs.comm.model.Resp;

@ControllerAdvice
public class CtlAdvice {

    private Logger logger = LoggerFactory.getLogger(CtlAdvice.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Object exceptionHandler(Exception e, HttpServletRequest request) {
        if (Constants.TEST_MODE)
            logger.error("exceptionHandler", e);

        String uri = request.getRequestURI();
        if (uri.contains("/rest")) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON_UTF8)
                    .body(new Resp(Code.REQUEST_ERR, e.getMessage()));
        } else if (uri.contains("/fs")) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentLength(0);
        } else {
            ModelAndView mv = new ModelAndView("err");
            mv.addObject("title", e.getMessage());
            mv.addObject("msg", e.getMessage());
            return mv;
        }
    }
}
